package com.lingnan.service.impl;

import com.lingnan.dto.AdminStatisticsDTO;
import com.lingnan.entity.vo.Result;
import com.lingnan.feign.JobPositionClient;
import com.lingnan.feign.UserFeignClient;
import com.lingnan.service.AdminStatisticsService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import static cn.dev33.satoken.SaManager.log;

@Service
@RequiredArgsConstructor
public class AdminStatisticsServiceImpl implements AdminStatisticsService {

    private final UserFeignClient userFeignClient;
    private final JobPositionClient jobPositionClient;

    @Override
    @Cacheable(key = "'adminStats'", unless = "#result == null")
    public AdminStatisticsDTO getAdminStatistics() {
        AdminStatisticsDTO statisticsDTO = new AdminStatisticsDTO();

        // 1. 获取用户统计
        statisticsDTO.setUserStatistics(getUserStatistics());

        // 2. 获取职位类型百分比
        try {
            Result<Map<String, Double>> jobTypeResult = jobPositionClient.getJobTypePercentages();
            if (jobTypeResult != null && jobTypeResult.isSuccess() && jobTypeResult.getData() != null) {
                statisticsDTO.setJobTypePercentages(jobTypeResult.getData());
            } else {
                log.error("JOB_TYPE_STATS_ERROR",
                        "获取职位类型百分比失败: " + (jobTypeResult != null ? jobTypeResult.getMessage() : "结果为空"));
            }
        } catch (Exception e) {
            log.error("JOB_TYPE_STATS_ERROR", "获取职位类型百分比异常", e);
        }

        // 3. 获取用户增长趋势
        statisticsDTO.setGrowthTrends(getUserGrowthTrends());

        // 4. 计算用户增长量和增长比
        statisticsDTO.setGrowthMetrics(calculateGrowthMetrics());

        return statisticsDTO;
    }

    private AdminStatisticsDTO.UserStatistics getUserStatistics() {
        AdminStatisticsDTO.UserStatistics stats = new AdminStatisticsDTO.UserStatistics();
        Map<String, Long> counts = userFeignClient.getUserCounts();

        stats.setJobSeekerCount(counts.getOrDefault("jobSeekers", 0L));
        stats.setCompanyUserCount(counts.getOrDefault("companies", 0L));
        stats.setHrUserCount(counts.getOrDefault("hrs", 0L));

        return stats;
    }

    private List<AdminStatisticsDTO.UserGrowthTrend> getUserGrowthTrends() {
        List<Integer> periods = Arrays.asList(7, 30, 90, 120, 365);
        return periods.parallelStream()
                .map(this::getUserGrowthTrend)
                .collect(Collectors.toList());
    }

    private AdminStatisticsDTO.UserGrowthTrend getUserGrowthTrend(int days) {
        AdminStatisticsDTO.UserGrowthTrend trend = new AdminStatisticsDTO.UserGrowthTrend();

        // 修正日期范围计算（包含起止日期共days天）
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(days - 1);
        trend.setDate(startDate.toString() + "至" + endDate.toString());

        Map<String, Long> growthData = userFeignClient.getUserGrowth(days);

        trend.setJobSeekerGrowth(growthData.getOrDefault("jobSeekers", 0L).intValue());
        trend.setCompanyUserGrowth(growthData.getOrDefault("companies", 0L).intValue());
        trend.setHrUserGrowth(growthData.getOrDefault("hrs", 0L).intValue());

        return trend;
    }

    private AdminStatisticsDTO.GrowthMetrics calculateGrowthMetrics() {
        AdminStatisticsDTO.GrowthMetrics metrics = new AdminStatisticsDTO.GrowthMetrics();
        LocalDate now = LocalDate.now();
        int currentMonth = now.getMonthValue();
        int currentYear = now.getYear();

        // 计算上个月的年月信息
        int prevMonth = currentMonth - 1;
        int prevYear = currentYear;
        if (prevMonth < 1) {
            prevMonth = 12;
            prevYear = currentYear - 1;
        }

        try {
            // 获取本月用户数量
            Map<String, Long> currentCounts = userFeignClient.getMonthlyCounts(currentYear, currentMonth);
            Long currentMonthJobSeeker = currentCounts.getOrDefault("jobSeekers", 0L);
            Long currentMonthCompanyUser = currentCounts.getOrDefault("companies", 0L);
            Long currentMonthHrUser = currentCounts.getOrDefault("hrs", 0L);

            // 获取上月用户数量
            Map<String, Long> prevCounts = userFeignClient.getMonthlyCounts(prevYear, prevMonth);
            Long prevMonthJobSeeker = prevCounts.getOrDefault("jobSeekers", 0L);
            Long prevMonthCompanyUser = prevCounts.getOrDefault("companies", 0L);
            Long prevMonthHrUser = prevCounts.getOrDefault("hrs", 0L);

            // 计算求职者增长
            metrics.setJobSeekerGrowth((int) (currentMonthJobSeeker - prevMonthJobSeeker));
            metrics.setJobSeekerGrowthRate(calculateGrowthRate(currentMonthJobSeeker, prevMonthJobSeeker));

            // 计算公司用户增长
            metrics.setCompanyUserGrowth((int) (currentMonthCompanyUser - prevMonthCompanyUser));
            metrics.setCompanyUserGrowthRate(calculateGrowthRate(currentMonthCompanyUser, prevMonthCompanyUser));

            // 计算HR用户增长
            metrics.setHrUserGrowth((int) (currentMonthHrUser - prevMonthHrUser));
            metrics.setHrUserGrowthRate(calculateGrowthRate(currentMonthHrUser, prevMonthHrUser));

        } catch (Exception e) {
            log.error("GROWTH_CALC_ERROR",
                    String.format("计算增长率错误 当前月:%d/%d 上月:%d/%d",
                            currentYear, currentMonth, prevYear, prevMonth), e);
        }
        return metrics;
    }

    private int calculateGrowthRate(long current, long previous) {
        if (previous == 0) {
            return current > 0 ? 100 : 0;
        }
        return (int) Math.round(((double)(current - previous) / previous) * 100);
    }
}